import { ActivatedRoute, Router } from '@angular/router';
import { Component } from '@angular/core';
import { CascaderItem, DValidateRules, DialogService, FormLayout, TableWidthConfig } from 'ng-devui';
import { Customer } from 'src/app/@core/data/customer';
import { AttachmentComponent } from 'src/app/@shared/components/attachment/attachment.component';
import { AddLinkManComponent } from '../add-customer/add-link-man/add-link-man.component';
import { CustomerService } from 'src/app/@core/services/customer/customer.service';
import { UserService } from 'src/app/@core/services/user/user.service';
import cityData from 'src/app/@core/mock/city.json';
import { SelectUserComponent } from 'src/app/@shared/components/select-user/select-user.component';
import { AddCustomerInvoiceComponent } from '../add-customer/add-customer-invoice/add-customer-invoice.component';
@Component({
  selector: 'app-edit-customer',
  templateUrl: './edit-customer.component.html',
  styleUrls: ['./edit-customer.component.scss']
})
export class EditCustomerComponent {
  user: any;
  device: any
  config = {
    maxHeight: '600px',
    width: '450px',
    backdropCloseable: true,
  }//弹窗配置
  tabActiveId: string | number = '基本信息';
  tableData = []
  DiscountOptions = []
  customer: Customer = {
    customerId: null, // 客户ID
    customerNum: null, // 客户编号
    customerAbbreviation: null, // 客户简称
    chineseName: null, // 中文名称
    englishName: null, // 英文名称
    account: null, // 账号
    password: null, // 密码
    customerClassId: null, // 客户分类
    customerClassName: null, // 客户分类名称
    customerType: true, // 客户类型
    salesType: true, // 销售类型
    salesmanId: null, // 业务员
    salesmanName: null, // 业务员名称
    customerDiscountId: null, // 客户折扣
    customerDiscountName: null,// 客户折扣名称
    customerCurrencyId: null, // 币种
    customerCurrencyName: null, // 币种名称
    country: '中国', // 国家
    province: '', // 省份
    city: '', // 城市
    district: '', // 区域
    address: null, // 地址
    deliveryCountry: '中国', // 送货国家
    deliveryProvince: '', // 送货省份
    deliveryCity: '', // 送货城市
    deliveryDistrict: '', // 送货区域
    deliveryAddress: null, // 送货地址
    invoiceAddress: null, // 发票地址
    phone: null, // 电话
    fax: null, // 传真
    email: null, // 邮箱
    contactPerson: null, // 联系人
    isInvoicing: false, // 是否开发票
    taxRate: 0.13, // 税率
    customerCollectionPeriodId: null, // 收款期限
    customerCollectionPeriodName: null, // 收款期限名称
    customerSettlementMethodId: null, // 结算方式
    customerSettlementMethodName: null, // 结算方式名称
    isCreditLimit: false, // 是否有信用限制
    note: '', // 备注
    annex: '', // 附件
    isEnabled: true, // 是否启用
    accountBalance: 0, // 账户余额
    createTime: null, // 创建时间
    customerContacts: [], // 客户联系人
    invoiceInformations: [], // 发票信息
  }
  tableWidthConfig2: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '100px'
    },
    {
      field: 'caozuo',
      width: '150px'
    },
    {
      field: 'showType',
      width: '150px'
    },
    {
      field: 'showType',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
  ];//表格宽度配置
  customerTypes = [
    {
      name: '真实客户',
      value: true
    },
    {
      name: '潜在客户',
      value: false
    },
  ]//客户类型
  salesTypes = [
    {
      name: '国内销售',
      value: true
    },
    {
      name: '国外销售',
      value: false
    }
  ]//销售类型
  taxCategorys = [
    '不计税', '内含税', '外加税'
  ];
  collectionPeriods = [
  ]
  settlementMethods = [
  ]
  staffNameoptions = []
  customerRules: { [key: string]: DValidateRules } = {
    customerNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*客户编号不能为空' },
        { minlength: 2, message: '*客户编号长度至少为2' },
        { maxlength: 40, message: '*客户编号长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*客户编号不能包含空格' }
      ]
    },
    customerAbbreviation: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*客户简称不能为空' },
        { minlength: 2, message: '*客户简称长度至少为2' },
        { maxlength: 40, message: '*客户简称长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*客户简称不能包含空格' }
      ]
    },
    chineseName: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*中文名称不能为空' },
        { minlength: 2, message: '*中文名称长度至少为2' },
        { maxlength: 40, message: '*中文名称长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*中文名称不能包含空格' }
      ]
    },
    customerClassId: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*客户分类不能为空' },
      ]
    },
  }
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: 'checkbox',
      width: '150px'
    },
    {
      field: 'caozuo',
      width: '150px'
    },
    {
      field: 'showType',
      width: '150px'
    },
    {
      field: 'showType',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
    {
      field: 'enabled',
      width: '150px'
    },
  ];//表格宽度配置
  customerCategorys = []
  layoutDirection: FormLayout = FormLayout.Horizontal;
  msgs: { severity: any; summary: any; content: any; }[];
  city = []
  address: any = [
    this.customer.province, this.customer.city, this.customer.district
  ]
  deliveryAddress: any = [
    this.customer.deliveryProvince, this.customer.deliveryCity, this.customer.deliveryDistrict
  ]
  pager = {
    total: 20,
    pageIndex: 1,
    pageSize: 20
  };
  customerClassId: any = []
  taxRate = this.customer.taxRate * 100
  customerId: any
  invoiceData: any = []
  currencyOptions: any = []
  constructor(private UserService: UserService, private CustomerService: CustomerService, private dialogService: DialogService, private Router: Router, private ActivatedRoute: ActivatedRoute) {
    this.city = cityData;
  }
  ngOnInit(): void {
    this.UserService.GetAllEmploy(1, 9999).subscribe((data: any) => {
      this.staffNameoptions = data.items
    })
    this.CustomerService.GetPagedCurrency(1, 9999).subscribe((data: any) => {
      this.currencyOptions = data.items
    })
    this.CustomerService.GetPagedSettlementMethod(1, 9999).subscribe((data: any) => {
      this.settlementMethods = data.items
    })
    this.CustomerService.GetPagedCustomerDiscount(1, 9999).subscribe((data: any) => {
      this.DiscountOptions = data.items
    })
    this.CustomerService.GetPagedCollectionPeriod({
      PageSize: 999,
      PageNumber: 1,
      SearchStatus: '收款'
    }).subscribe((data: any) => {
      this.collectionPeriods = data.items
    })
    this.ActivatedRoute.params.subscribe((params: any) => {
      this.CustomerService.GetPagedCustomerClassWithSub(1, 9999).subscribe((data: any) => {
        this.customerCategorys = this.convertToCascaderItem(data)
        this.customerId = params.id
        this.CustomerService.GetCustomerById(this.customerId).subscribe((data: any) => {
          this.customer = data
          this.tableData = data.customerContacts
          this.invoiceData = data.invoiceInformations
          this.customerClassId = this.findPath(this.customerCategorys, data.customerClassId)
          this.taxRate = data.taxRate * 100
          this.address = [data.province, data.city, data.district]
          this.deliveryAddress = [data.deliveryProvince, data.deliveryCity, data.deliveryDistrict]
        })
      })
    })
  }
  remove(i: number) {
    this.tableData.splice(i, 1);
  }//删除人员
  selectUser(index: number, dialogtype?: string,) {
    let data = {
      user: this.user,
      display: false,
      placeholder: '请选择人员'
    };
    const results = this.dialogService.open({
      id: 'department',
      width: '800px',
      title: '人员',
      data: data,
      content: SelectUserComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.selectData) {
              if (this.tableData.some(item => item.employeeCode === results.modalContentInstance.selectData.employeeCode)) {
                this.showToast('error', '错误', '不能重复选择人员');
              } else {
                this.tableData[index].id = results.modalContentInstance.selectData.id;
                this.tableData[index].employeeCode = results.modalContentInstance.selectData.employeeCode;
                this.tableData[index].name = results.modalContentInstance.selectData.name;
                this.tableData[index].ownerPhoneNumber = results.modalContentInstance.selectData.ownerPhoneNumber;
                this.tableData[index].departmentId = results.modalContentInstance.selectData.departmentId;
              }
              results.modalInstance.hide();
            }
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }//人员信息
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  }//提示框
  submit($event: any) {
    this.customer.customerClassId = this.customerClassId[this.customerClassId.length - 1]
    this.customer.createTime = new Date()
    this.customer.customerContacts = this.tableData
    this.customer.invoiceInformations = this.invoiceData
    if ($event.valid) {
      this.CustomerService.UpdateCustomer(this.customer.customerId, this.customer).subscribe((data: any) => {
        this.showToast('success', '成功', '更新成功');
        setTimeout(() => {
          this.Router.navigate(['/pages/basicdata/customer'])
        }, 1000);
      }, (error) => {
        if(error.status==404){
          this.showToast('error', '失败', '服务器连接失败');
        }else{
          this.showToast('error', '失败', error.error);
        }
      }
      )
    }
  }
  cancle() {
    this.Router.navigate(['/pages/basicdata/customer'])
  }
  onButtonClick(dialogtype?: string) {
    const results = this.dialogService.open({
      title: '客户附件',
      width: '800px',
      backdropCloseable: false,
      data: {
        data: '工序附件',
        urls: this.customer.annex
      },
      content: AttachmentComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.customer.annex = results.modalContentInstance.urls;
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  addLinkMan(dialogtype?: string) {
    let data = {
      display: false
    };
    const results = this.dialogService.open({
      id: '添加联系人',
      ...this.config,
      title: '添加联系人',
      data: data,
      content: AddLinkManComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.form.customerContactName) {
              if(results.modalContentInstance.form.isDefault){
                this.tableData.forEach(item=>{
                  item.isDefault = false
                })
              }
              this.tableData.push(results.modalContentInstance.form)
              results.modalInstance.hide();
            }
            data.display = true;
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  removeInvoice(i: number) {
    this.invoiceData.splice(i, 1);
  }//删除发票信息
  editLinkMan(rowItem: any, i: any, dialogtype?: string) {
    let data = {
      display: false,
      rowItem: rowItem
    };
    const results = this.dialogService.open({
      id: '编辑联系人',
      ...this.config,
      title: '编辑联系人',
      data: data,
      content: AddLinkManComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.form.customerContactName) {
              if(results.modalContentInstance.form.isDefault){
                this.tableData.forEach(item=>{
                  item.isDefault = false
                })
              }
              this.tableData[i] = results.modalContentInstance.form;
              results.modalInstance.hide();
            }
            data.display = true;
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  cityChange() {
    this.customer.province = this.address[0]
    this.customer.city = this.address[1]
    this.customer.district = this.address[2]
  }
  CollectionPeriodChange($event: any) {
    this.customer.customerCollectionPeriodName = $event.collectionPeriodName
  }
  settlementMethodsChange($event: any) {
    this.customer.customerSettlementMethodName = $event.settlementMethodName
  }
  customerDiscountChange($event: any){
    this.customer.customerDiscountName = $event.customerDiscountName
  }
  currencyOptionsChange($event: any) {
    this.customer.customerCurrencyName = $event.currencyName
  }
  staffNameoptionsChange($event: any) {
    this.customer.salesmanName = $event.name
  }
  customerClassChange($event: any) {
    this.customer.customerClassId = this.customerClassId[this.customerClassId.length - 1]
    this.customer.customerClassName = this.findLabelById(this.customerCategorys, this.customer.customerClassId)
  }
  findLabelById(categories: any, value: number): string | undefined {
    for (const category of categories) {
      if (category.value === value) {
        return category.label;
      }
      if (category.children) {
        const foundLabel = this.findLabelById(category.children, value);
        if (foundLabel) {
          return foundLabel;
        }
      }
    }
    return undefined; // 如果没有找到匹配的id，返回undefined
  }
  taxRateChange() {
    this.customer.taxRate = this.taxRate / 100
  }
  deliveryCityChange() {
    this.customer.deliveryProvince = this.deliveryAddress[0]
    this.customer.deliveryCity = this.deliveryAddress[1]
    this.customer.deliveryDistrict = this.deliveryAddress[2]
  }
  convertToCascaderItem(data: any[]): CascaderItem[] {
    return data.map(item => {
      let cascaderItem: CascaderItem = {
        label: item.customerClassName,
        value: item.customerClassId,
        pid: item.parentCustomerClassId,
      };
      if (item.subCustomerClasses) {
        cascaderItem.children = this.convertToCascaderItem(item.subCustomerClasses);
      }
      return cascaderItem;
    });
  }//转换数据格式为华为库练级菜单的数据格式
  findDepartmentByValue(arr: string | any[], value: any, parent = null) {
    for (let i = 0; i < arr.length; i++) {
      if (arr[i].value === value) {
        return parent ? parent : arr[i];
      } else if (Array.isArray(arr[i].children) && arr[i].children.length > 0) {
        const result = this.findDepartmentByValue(arr[i].children, value, arr[i]);
        if (result) {
          return result;
        }
      }
    }
    return null;
  }//根据value查找部门
  findPath(data: any, value: any, path = []) {
    for (const item of data) {
      const newPath = [...path, item.value];
      if (item.value === value) {
        return newPath;
      }
      if (item.children && item.children.length > 0) {
        const result = this.findPath(item.children, value, newPath);
        if (result.length) {
          return result;
        }
      }
    }
    return [];
  }
  addCustomerInvoice(dialogtype?: string) {
    let data = {
      display: false
    };
    const results = this.dialogService.open({
      id: '添加开票信息',
      ...this.config,
      title: '添加开票信息',
      data: data,
      content: AddCustomerInvoiceComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.form.invoiceHeader) {
              results.modalContentInstance.form.createTime = new Date()
              this.invoiceData.push(results.modalContentInstance.form)
              results.modalInstance.hide();
            }
            data.display = true;
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  editCustomerInvoice(rowItem: any, i: any, dialogtype?: string) {
    let data = {
      display: false,
      rowItem: rowItem
    };
    const results = this.dialogService.open({
      id: '添加开票信息',
      ...this.config,
      title: '添加开票信息',
      data: data,
      content: AddCustomerInvoiceComponent,
      dialogtype: dialogtype,
      onClose: () => {
      },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            if (results.modalContentInstance.form.invoiceHeader) {
              results.modalContentInstance.form.createTime = new Date()
              this.invoiceData[i] = results.modalContentInstance.form
              results.modalInstance.hide();
            }
            data.display = true;
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
}
